package com.mrd.gtimp.business.action;

import com.mrd.exception.QueryException;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.business.entity.Attachment;
import com.mrd.gtimp.business.service.AttachmentBiz;
import com.opensymphony.xwork2.ActionSupport;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.InputStream;

import javax.annotation.Resource;

@SuppressWarnings("serial")
@Controller
@RequestMapping("/business")
public class DownloadAction extends ActionSupport {

    private String downloadFileName; // 下载文件的名字

    private String path;            // 下载文件的路径

    private Attachment attachment;

    @Resource
    private AttachmentBiz attachmentBiz;

    @RequestMapping("/download-execute")
    public String execute() throws Exception {
        try {
            if (null != attachment) {
                Attachment at = attachmentBiz.findEntityById(attachment.getId());
                downloadFileName = at.getName();
                // 解决下载文件名的中文乱码
                downloadFileName = new String(downloadFileName.getBytes("gb2312"), "ISO-8859-1");

                // path = at.getReplacename();
                path = at.getPath();
//                HttpServletRequest request = ServletActionContext.getRequest();
                @SuppressWarnings("deprecation")
                String realPath = HttpUtils.getRequest().getRealPath("/");
                File file = new File(realPath.substring(0, realPath.length() - 1) + path);
                if (file.exists() && file.isFile()) {
                    return SUCCESS;
                } else {
                    return "noFile";
                }
            }
        } catch (QueryException e) {
            e.printStackTrace();
        }
        //// TODO: 2016/8/15  SUCCESS
        return null;
    }

    public InputStream getInputStream() throws Exception {
        // return new FileInputStream(getPath()); //使用此方式时：getPath()为绝对路径
        return HttpUtils.getServletContext().getResourceAsStream(getPath()); // 使用此方式时：
        // 资源放在WEB-INF目录下，并且getPath()的值必须以"\WEB-INF\"开始
    }

    public String getDownloadFileName() {
        return downloadFileName;
    }

    public void setDownloadFileName(String downloadFileName) {
        this.downloadFileName = downloadFileName;
    }

    public Attachment getAttachment() {
        return attachment;
    }

    public void setAttachment(Attachment attachment) {
        this.attachment = attachment;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

}
